`define MemSize 32768 // 32K,8000h
// `define MemSize 4096 // 4K,1000h
//0-3000h: IM, 3000h-4000h: DM
module Mem(
        input MemWr,
        input MemRd,
        input [31:0] Addr,
        input [31:0] W_data,
        output reg [31:0] R_data
    );
    reg [31:0] Memory[0:`MemSize-1];

    // Initialize Memory
    integer i=0;
    initial begin
        for (i = 0; i < `MemSize; i = i + 1)
            Memory[i] = 32'd0;

        // 从文件的偏移地址开始读取
        $readmemh("code.txt", Memory);

        // // 在地址 0x00003000 之后的 10 个地址放置数值 1 到 10
        // // 0x00003000: 1, 0x00003004: 2, 0x00003008: 3, ...
        // for (i = 0; i < 10; i = i + 1)
        //     Memory[8'h300 + i] = i + 1;
    end


    // Read Memory
    // assign R_data=(MemRd==1'b1)?Memory[(Addr)>>2]:32'd0;
    always @(MemRd) begin
        if(MemRd) begin
            if(Addr>=32'h00003000)
                R_data <= Memory[(Addr)>>2]; //instruction
            else
                R_data <= Memory[(Addr+32'h00004000)>>2]; //data
        end
    end

    // Write Memory or flash Memory
    always @(MemWr) begin
        if(MemWr) begin
            Memory[(Addr+32'h00004000)>>2]<=W_data;  //数据地址从0开始，映射到3000h
        end
    end

endmodule






